//
//  RecommendViewController.m
//  Qyer
//
//  Created by 赵宇 on 15/9/8.
//  Copyright (c) 2015年 赵宇. All rights reserved.
//

#import "RecommendViewController.h"

#import "TOTOTableViewCell.h"
#import "TOTOTOCollectionViewCell.h"
@interface RecommendViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UIGestureRecognizerDelegate>

@end

@implementation RecommendViewController
-(void)dealloc
{
    [_recommendTableview release];
    [_titleScroll release];
    [_pageControl release];
    [_titleInforArr release];
    [_findInfArr release];
    [_lookhotInforArr release];
    [_urlArr release];
    [_headView release];
    [_titlescrollTimer release];
    [super dealloc];
}
-(void)viewWillAppear:(BOOL)animated
{
    [_recommendTableview reloadData];
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBarHidden = YES;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.page = 1;
    
//     签完UIGestureRecognizerDelegate代理,然后写这两句话,效果就是从这个页面push的其他页面都可以右滑返回上一页
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;

    
    [self getLookHotTravelInformatiom:1 isDown:YES];
    [self creatNav];
    
    
}

-(void)creatNav
{
// 创建一个假的Navigation
    UIView *nav = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    nav.backgroundColor = [UIColor colorWithRed:34./255 green:169./ 255 blue:118./255 alpha:1];
//然后加个假的搜索Button按钮,一点就跳到搜索页面
    UIButton *search = [UIButton buttonWithType:UIButtonTypeCustom];
    search.frame = CGRectMake(70, 25, SCREEN_WIDTH-140, 30);
    search.layer.masksToBounds = YES;
    search.layer.cornerRadius = 10.;
    [search addTarget:self action:@selector(goToSearchView) forControlEvents:UIControlEventTouchUpInside];
    search.backgroundColor = [UIColor colorWithRed:27./255 green:129./255 blue:94./255 alpha:1];
    search.titleLabel.font = [UIFont systemFontOfSize:15.];
    [search setTitle:@"🔍  搜索帖子" forState:UIControlStateNormal];
    [nav addSubview:search];
    [self.view addSubview:nav];
    
    [nav release];
}
-(void)goToSearchView
{
// 搜索帖子页面
    BookViewController *book = [[BookViewController alloc]init];
    UINavigationController *BNavC = [[UINavigationController alloc]initWithRootViewController:book];
    [self presentViewController:BNavC animated:YES completion:nil];
    
    [BNavC release];
    [book release];

}

-(void)getLookHotTravelInformatiom:(NSInteger)number isDown:(BOOL)down;
{
#pragma mark - 用Down判断是不是下拉刷新,因为下拉不需要改变网址的参数
    if (down) {
        self.page = 1;
        self.titleInforArr = [[NSMutableArray alloc]init];
        self.findInfArr = [[NSMutableArray alloc]init];
        self.lookhotInforArr = [[NSMutableArray alloc]init];

    NSString *string = @"http://open.qyer.com/qyer/recommands/entry?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&page=1&track_app_channel=App%2520Store&track_app_version=6.6&track_device_info=iPhone%25204%28ChinaMobile%2CChinaUnicom%29&track_deviceid=301FBCE0-A789-4EAC-ADF1-95E1AACF2A70&track_os=ios%25207.1.2&v=1";
    [AFNblock getdataWithString:string block:^(id block) {
        NSDictionary *bigDic = block;
        NSDictionary *dataDic = [bigDic objectForKey:@"data"];
        NSArray *slideArr = [dataDic objectForKey:@"slide"];
        NSArray *subjectArr = [dataDic objectForKey:@"subject"];
// 轮播图数组
        for (int i = 0; i <slideArr.count; i++) {
            NSDictionary *dic = [slideArr objectAtIndex:i];
            SlideModel *slidemodel = [[SlideModel alloc]initWithDictionary:dic];
            [_titleInforArr addObject:slidemodel];
        }
// 发现下一站
        for (int i = 0; i < subjectArr.count; i++) {
            NSDictionary *dic = [subjectArr objectAtIndex:i];
            SlideModel *findmodel = [[SlideModel alloc]initWithDictionary:dic];
            [_findInfArr addObject:findmodel];
        }

        if (_recommendTableview == nil) {
            
        [self scrollPicture];
        [self creatTableview];
        }
    
        [_recommendTableview reloadData];
        [_recommendTableview.header endRefreshing];
       
       
        [self.lookHTCell.collection reloadData];
    }];
    
        
}
#pragma mark - 如果up是NO,说明是上拉加载,每拉一次number+1,但是穷游的接口数据库里,只有4页,就以也就只能拉4次就没有新数据了
     NSString *str = [NSString stringWithFormat:@"http://open.qyer.com/qyer/recommands/trip?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&oauth_token=d5ecb9febb61510d54ba2d47d986cf65&page=%ld&track_app_version=6.6.6&track_deviceid=301FBCE0-A789-4EAC-ADF1-95E1AACF2A70&track_user_id=6695170&type=index&v=1",(long)number];
    
    [AFNblock getdataWithString:str block:^(id block) {
        NSDictionary *bigDic = block;
        NSArray *dataArr = [bigDic objectForKey:@"data"];
        for (NSDictionary *dic in dataArr) {
            LookHotTravelModel *lookhotmodel = [[LookHotTravelModel alloc]initWithDictionary:dic];
            [_lookhotInforArr addObject:lookhotmodel];
        }
        // 获取完数据,停止刷新
        [_recommendTableview.footer endRefreshing];
        [_recommendTableview reloadData];
        [self.lookHTCell.collection reloadData];
     }];
   
}
-(void)xiala
{
    __block RecommendViewController *REC = self;
    [_recommendTableview addLegendHeaderWithRefreshingBlock:^{
        
        [REC getLookHotTravelInformatiom:1 isDown:YES];
        
    }];
}
-(void)shangla
{
    __block RecommendViewController *rec = self;
    [_recommendTableview addLegendFooterWithRefreshingBlock:^{
        rec.page += 1;
        if (rec.page < 5)
        {
            [rec getLookHotTravelInformatiom:rec.page isDown:NO];
        }else
        {
            rec.page = 5;
            [_recommendTableview.footer endRefreshing];
        }

    }];
}
#pragma mark - 创建轮播图
-(void)scrollPicture
{
    _headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/5*2)];
    _titleScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/5*2)];
    [_titleScroll setContentSize:CGSizeMake(SCREEN_WIDTH*(_titleInforArr.count + 2), 0)];
    [_titleScroll setContentOffset:CGPointMake(SCREEN_WIDTH, 0)];
    [_titleScroll setPagingEnabled:YES];
    [_titleScroll setBounces:NO];
    [_titleScroll setDelegate:self];
    [_titleScroll showsHorizontalScrollIndicator];
    
    _titlescrollTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(titleScrollTimer) userInfo:nil repeats:YES];
    
    [_headView addSubview:_titleScroll];
    
//把图片和URL分辨放在一个大数组里,方便button的image和点击方法的赋值
    NSMutableArray *photoViewArr = [[NSMutableArray alloc]init];
    _urlArr = [[NSMutableArray alloc]init];
    for (int i = 0; i< _titleInforArr.count; i++)
    {
        SlideModel *model = [_titleInforArr objectAtIndex:i];
        [_urlArr addObject:model.url];
            // 下载图片
        NSURL *url = [NSURL URLWithString:model.photo];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *photoImage = [UIImage imageWithData:data];
        [photoViewArr addObject:photoImage];
    }

//在左右各添加一张假图
    for (int i = 0; i < _titleInforArr.count+2; i++) {
        UIButton *slideButton = [UIButton buttonWithType:UIButtonTypeCustom];
        slideButton.frame = CGRectMake(i*SCREEN_WIDTH, 0, SCREEN_WIDTH, _titleScroll.frame.size.height);
        [slideButton addTarget:self action:@selector(nextbuttonClick:) forControlEvents:UIControlEventTouchUpInside];
        if (i == 0)
            {
              [slideButton setImage:[photoViewArr objectAtIndex:photoViewArr.count-1] forState:UIControlStateNormal];
            }if (i>0&&i<_titleInforArr.count+1)
            {
              [slideButton setImage:[photoViewArr objectAtIndex:i-1] forState:UIControlStateNormal];
            }if (i == _titleInforArr.count +1)
            {
               [slideButton setImage:[photoViewArr objectAtIndex:0] forState:UIControlStateNormal];
            }
                slideButton.tag = 2000+i;
                [_titleScroll addSubview:slideButton];
        }
    
#pragma  mark  创建pageControl,给pageControl添加target
    _pageCount = 1;
    _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/4, _titleScroll.frame.size.height -40, SCREEN_WIDTH/2, 40)];
    [_pageControl setNumberOfPages:_titleInforArr.count];
    [_pageControl addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_pageControl];
    [self.view addSubview:_headView];
    [_headView addSubview:_pageControl];
    
    
    [_headView release];
    [_titleScroll release];
    [photoViewArr release];
    [_pageControl release];
    
    
    
    [_titleInforArr release];
}
-(void)titleScrollTimer
{
    [_titleScroll setContentOffset:CGPointMake(_pageCount * SCREEN_WIDTH, 0) animated:YES];
    _pageCount++;
}
-(void)nextbuttonClick:(UIButton *)sender
{
    SlideViewController *slideviewController = [[SlideViewController alloc]init];
    for (int i = 0; i < _urlArr.count; i++) {
        if (sender.tag == i + 2001) {
            slideviewController.url = [_urlArr objectAtIndex:i];
        }
    }
    [self.navigationController pushViewController:slideviewController animated:YES];
    
    [slideviewController release];
}
#pragma mark - pageControl的点击方法,点击小圆点轮播图滚动
-(void)changePage:(UIPageControl *)page
{
     [_titleScroll setContentOffset:CGPointMake(page.currentPage * SCREEN_WIDTH, 0) animated:YES];
}
#pragma mark - 把Scroll和小圆点关联,titleScroll的方法:滚动就调用
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 偏移量/当页宽度 = 当前第几页
        _pageCount = _titleScroll.contentOffset.x / _titleScroll.frame.size.width;
    
        if (_pageCount == _titleInforArr.count + 1) {
            [_titleScroll setContentOffset:CGPointMake(_titleScroll.frame.size.width, 0) animated:NO];
            _pageCount = 1;
        }
        if (_titleScroll.contentOffset.x == 0) {
            [_titleScroll setContentOffset:CGPointMake(_titleInforArr.count * SCREEN_WIDTH, 0) animated:NO];
        }
    [_pageControl setCurrentPage:_titleScroll.contentOffset.x / _titleScroll.frame.size.width - 1];
    
}

-(void)creatTableview
{
    _recommendTableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-112) style:UITableViewStylePlain];
    _recommendTableview.tableHeaderView = _headView;
    [_recommendTableview setDelegate:self];
    [_recommendTableview setDataSource:self];
    [_recommendTableview reloadData];
    
    [self.view addSubview:_recommendTableview];
    [self shangla];
    [self xiala];
  
    [_recommendTableview release];
}
#pragma mark - tableview代理
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row ==  0) {
        return  SCREEN_HEIGHT/3;
    }if (indexPath.row < _findInfArr.count-1) {
        return SCREEN_WIDTH/3;
    }
    else{
        return SCREEN_WIDTH/4+10;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // indexPath.row == 1是CollectionView,所以点击方法在Collection的代理方法里实现
    if (indexPath.row == 0)
    {
        SlideViewController *findview = [[SlideViewController alloc]init];
        SlideModel *mol = [_findInfArr objectAtIndex:indexPath.row];
        findview.url = mol.url;
        [self.navigationController pushViewController:findview animated:YES];
    }if (indexPath.row > 1)
    {
        SlideViewController *lookhotView = [[SlideViewController alloc]init];
        LookHotTravelModel *mol = [_lookhotInforArr objectAtIndex:indexPath.row-2];
        lookhotView.url = mol.view_url;
        [self.navigationController pushViewController:lookhotView animated:YES];

    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _lookhotInforArr.count + _findInfArr.count - 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row ==  0)
    {
        static NSString *findcellid = @"findcellid";
        FindNextStationTableViewCell *findcell = [tableView dequeueReusableCellWithIdentifier:findcellid];
        if (!findcell) {
            findcell = [[FindNextStationTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:findcellid];
        }
        SlideModel *findmodel = [_findInfArr objectAtIndex:indexPath.row];
        [findcell setUpWithModel:findmodel];
       
        return findcell;
    }
    if (indexPath.row == 1) {
        static NSString *lookHTCellid = @"lookHTCellID";
        self.lookHTCell = [tableView dequeueReusableCellWithIdentifier:lookHTCellid];
        if (!self.lookHTCell) {
            self.lookHTCell = [[TOTOTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:lookHTCellid];
        }
        [self.lookHTCell setDelegate:self];
        [self.lookHTCell setDataSource:self];
        return self.lookHTCell;
        
    }
    else{
        static NSString *lookHotTravelcellid = @"lookhotcell";
        LookHotTravelTableViewCell *lookhotcell = [tableView dequeueReusableCellWithIdentifier:lookHotTravelcellid];
        if (!lookhotcell) {
            lookhotcell = [[LookHotTravelTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:lookHotTravelcellid];
        }
        LookHotTravelModel *lookmodel = [_lookhotInforArr objectAtIndex:indexPath.row-2];
        [lookhotcell setUpWithModel:lookmodel];
        return lookhotcell;
     }
    
}
#pragma mark - collection方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
        return 2;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TOTOTOCollectionViewCell *nextCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"lookHT" forIndexPath:indexPath];
     SlideModel *findmol = [_findInfArr objectAtIndex:indexPath.row+1];
    NSURL *url = [NSURL URLWithString:findmol.photo];
    [nextCell.advImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"zhanweiPic"]];
    return nextCell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        SlideViewController *nextView = [[SlideViewController alloc]init];
        SlideModel *mol = [_findInfArr objectAtIndex:1];
        nextView.url = mol.url;
        [self.navigationController pushViewController:nextView animated:YES];
        
    }else{
        SlideViewController *nextView = [[SlideViewController alloc]init];
        SlideModel *mol = [_findInfArr objectAtIndex:2];
        nextView.url = mol.url;
        [self.navigationController pushViewController:nextView animated:YES];
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
